<template>
  <div class="doctor-list-container">
    <Header style="margin-bottom: 20px"/>

    <!-- 部门信息 -->
    <el-card class="department-info">
      <div class="info-header">
        <el-icon :size="32">
          <OfficeBuilding/>
        </el-icon>
        <h2>{{ currentDepartment.name }}</h2>
      </div>
      <p class="description">{{ currentDepartment.description }}</p>
    </el-card>

    <!-- 医生列表 -->
    <el-skeleton :loading="loading" :rows="6" animated>
      <template #default>
        <el-row :gutter="20">
          <el-col
              v-for="doctor in doctors"
              :key="doctor.doctorId"
              :xs="24" :sm="12" :md="8" :lg="6"
          >
            <el-card class="doctor-card">
              <template #header>
                <div class="doctor-header">
                  <el-avatar :size="60" :src="doctor.avatar !== ''? doctor.avatar : defaultAvatar"/>
                  <div class="doctor-info">
                    <h3>{{ doctor.doctorRealName }}</h3>
                    <p class="title">{{ doctor.title }}</p>
                  </div>
                </div>
                <div>
                  <p>{{ doctor.description }}</p>
                </div>
              </template>

              <div class="doctor-details">
                <el-tag type="info">科室：{{ currentDepartment.name }}</el-tag>
                <el-rate
                    v-model="doctor.rating"
                    disabled
                    show-score
                    :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                />
              </div>

              <div class="action-buttons">
                <el-button
                    type="primary"
                    @click="handleConsult(doctor)"
                >在线咨询
                </el-button>
                <el-dialog title="在线咨询" v-model="chatDialogVisible">
                  <Chat :chatData="{doctorId: doctor.doctorId, userId: getUserInfo().userId}" :key="refreshKey"/>
                </el-dialog>
                <el-button
                    type="success"
                    @click="handleAppointment()"
                >预约挂号
                </el-button>
                <el-dialog title="预约挂号" v-model="consultDialogVisible">
                  <el-form label-width="80px" :model="consultData">
                    <el-form-item label="预约时间">
                      <el-date-picker type="datetime" placeholder="选择日期时间" v-model="consultData.appointTime">
                      </el-date-picker>
                    </el-form-item>
                    <el-form-item label="预约原因">
                      <el-input type="textarea" v-model="consultData.consultReason"></el-input>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button type="danger" @click="handleConsultCancel">取消</el-button>
                    <el-button type="primary" @click="fetchAppointment(doctor)">确定</el-button>
                  </div>
                </el-dialog>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 空状态 -->
        <el-empty
            v-if="!loading && doctors.length === 0"
            description="暂无医生信息"
        />
      </template>
    </el-skeleton>
  </div>
</template>

<script setup>
import {getAuth, getUserInfo} from '@/utils/auth';
import {dayjs, ElMessage} from 'element-plus';
import {useRoute, useRouter} from 'vue-router';
import {onMounted, ref} from "vue";
import {OfficeBuilding} from "@element-plus/icons-vue";
import {getDepartmentOne, getDoctorListByDepartment} from "@/api/department.js";
import {appointmentInsert} from "@/api/appointment.js";
import Chat from "@/views/Chat.vue";
const consultDialogVisible = ref(false)

const route = useRoute();
const router = useRouter();
const departmentId = route.params.id;
const refreshKey = ref(0)

const consultData = ref({})
const chatDialogVisible = ref(false)

const handleConsultCancel = () => {
  consultDialogVisible.value = false
  consultData.value = {}
}

// 模拟数据
const currentDepartment = ref({})

const doctors = ref([])

const loading = ref(true)
const defaultAvatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'

const pageData = ref({
  page: 1,
  size: 10,
});

// 获取数据
const fetchData = async () => {
  try {
    pageData.value.departmentId = departmentId
    const res = await getDoctorListByDepartment(pageData.value)
    doctors.value = res.data.records
    pageData.value.total = res.data.total
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

const fetchDepartment = async () => {
  try {
    const res = await getDepartmentOne(departmentId)
    currentDepartment.value = res.data
  } catch (error) {
    ElMessage.error('获取科室信息失败')
  } finally {
    // 处理获取到的科室信息
  }
}

// 处理咨询/预约
const handleConsult = (doctor) => {
  chatDialogVisible.value = true
  refreshKey.value += 1
}

const handleAppointment = () => {
  consultDialogVisible.value = true
}

const fetchAppointment = async (doctor) => {
  // 处理预约信息
  consultData.value.doctorId = doctor.doctorId
  consultData.value.departmentId = Number(departmentId)
  consultData.value.userId = getUserInfo().userId
  // 处理预约时间
  consultData.value.appointTime = dayjs(consultData.value.appointTime).format('YYYY-MM-DD HH:mm:ss');

  const res = await appointmentInsert(consultData.value)
  if (res.code === 200) {
    ElMessage.success('预约成功')
    consultDialogVisible.value = false
    consultData.value = {}
  } else {
    ElMessage.error('预约失败')
    consultData.value = {}
  }


}

onMounted(() => {
  fetchData()
  fetchDepartment()
})
</script>

<style scoped>
.doctor-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.department-info {
  margin-bottom: 30px;
  .info-header {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  .description {
    color: #666;
    margin-top: 10px;
  }
}

.doctor-card {
  margin-bottom: 20px;
  .doctor-header {
    display: flex;
    align-items: center;
    gap: 15px;
    .doctor-info {
      h3 { margin: 0; }
      .title { color: #666; margin: 5px 0; }
    }
  }
  .doctor-details {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin: 15px 0;
  }
  .action-buttons {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
  }
}
</style>
